import { Http2ServerRequest } from 'http2'

/*
 * @Author: H.
 * @Date: 2021-12-29 18:31:55
 * @LastEditTime: 2021-12-29 19:24:24
 * @Description: e
 */
import * as http from 'http'
import * as fs from 'fs'
import * as p from 'path'
import * as url from 'url'

const server = http.createServer() // http.server 类的实例
const publicDir = p.resolve(__dirname, 'public')
let cacheAge = 3600 * 24 * 365

server.on(
  'request',
  (request: http.IncomingMessage, response: http.ServerResponse) => {
    const { method, url: path, headers } = request
    const { pathname } = url.parse(path)
    // response.setHeader('Content-Type', 'text/html; charset=utf-8')
    if (method !== 'GET') {
      response.statusCode = 405
      response.end()
      return
    }

    let filename = pathname.substr(1)
    if (filename === '') {
      filename = 'index.html'
    }
    fs.readFile(p.resolve(publicDir, filename), (error, data) => {
      if (error) {
        console.log(error);

        if (error.errno === -2) {
          response.statusCode = 404
          fs.readFile(p.resolve(publicDir, '404.html'), (error, data) => {
            response.end(data)
          })

        } else if (error.errno === -21) {
          response.statusCode = 403
          response.end('无权访问该目录内容')
        } else {
          response.statusCode = 500
          response.end('服务器繁忙，请稍后再试')
        }

      } else {
        // 返回文件内容
        response.setHeader('Cache-Control', `public, max-age=${cacheAge}`)
        response.end(data)
      }
    })
  }
)

// 启动 HTTP 服务器监听连接
server.listen(8888)
